# -*- conding:utf-8 -*-
import requests
import ssl
from datetime import datetime
import socket

def check_https(url):
    result = {}
    try:
        # 建立 SSL 连接
        context = ssl.create_default_context()
        with socket.create_connection((url, 443),timeout=1) as sock:
            with context.wrap_socket(sock, server_hostname=url) as ssock:
                # 获取证书信息
                cert = ssock.getpeercert()
                valid_from = datetime.strptime(cert['notBefore'], "%b %d %H:%M:%S %Y %Z")
                valid_to = datetime.strptime(cert['notAfter'], "%b %d %H:%M:%S %Y %Z")

        # 计算有效期天数
        today = datetime.now()
        remaining_days = (valid_to - today).days

        # 存储状态和剩余天数
        result['status'] = 'valid'
        result['remaining_days'] = remaining_days

    except ssl.SSLError as e:
        result['status'] = 'invalid'
        result['error'] = str(e)

    except requests.exceptions.RequestException as e:
        result['status'] = 'request_error'
        result['error'] = str(e)

    except socket.gaierror:
        result['status'] = 'invalid'
        result['error'] = '无法解析主机名'
    
    except socket.timeout:
        result['status'] = 'timeout_error'
        result['error'] = '请求超时'

    except ConnectionRefusedError:
        result['status'] = 'connection_refused_error'
        result['error'] = '连接被拒绝'

    except ConnectionResetError:
        result['status'] = 'connection_reset_error'
        result['error'] = '强迫关闭连接'
    except ssl.CertificateError:
        result['status'] = 'invalid'
        result['error'] = '无法解析主机名'
    except OSError:
        result['status'] = 'No route to host'
        result['error'] = '无法访问目标主机'
    return result

# 输入你要监控的网站主机名
if __name__ == '__main__':
    website_url = "www.test.com"
    result_dict = check_https(website_url)
    print(result_dict)

